<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";
import { formatDate } from "@/utils";
import { ElMessage } from "element-plus";

const { pageData, agrMap } = useData();
import { deleteData, getDataByPage, exportData, importData, downloadTemplate } from "@/api/modules/resource/host-finger";
import UpdateForm from "./components/UpdateForm/index.vue";
import moment from "moment";
import { onMounted, ref } from "vue";

const heTableRef = ref(null);
const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);

interface Props {
  title?: string;
  defaultSelect?: string;
  rowData?: Object;
  maxMultipleNum?: number;
}

const props = withDefaults(defineProps<Props>(), {
  title: "选择指纹样例",
  defaultSelect: "",
  rowData: undefined,
  maxMultipleNum: 1000
});
const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {
    pageSize: 10000
  },
  responseKey: {
    list: "data",
    total: "total"
  }
});
const emit = defineEmits(["update"]);

function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize,
      name: formData.name,
      text: formData.text
    }
  });
}

function reloadDataCb() {
  reloadData();
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize,
      name: formData.name,
      text: formData.text
    }
  });
}

loadDataCb();

/**删除*/
import useDelete from "@/hooks/useDelete";
import { computed } from "vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import { Upload } from "@element-plus/icons-vue";

const { deleteHandler, idList } = useDelete();

async function deleteCb(id) {
  await deleteHandler({
    api: deleteData,
    multiple: false,
    sendData: {
      id
    },
    hideMessageBox: false
  });
  loadDataCb();
}

function selectCb(data) {
  console.log(data);
  emit("update", data);
  idList.value = data.rowList.map(item => item.userId);
}

const urlDownload = function (url, name) {
  var a = document.createElement("a");
  // console.log(url)
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  const clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

async function templateOperate(type) {
  if (type === "export") {
    const res = await exportData();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "download") {
    const res = await downloadTemplate();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_template_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await importData({ file: tempInput.files[0] });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}

onMounted(async () => {
  await loadDataCb();
  setTimeout(() => {
    console.log("props.defaultSelect", props.defaultSelect);
    if (!props.defaultSelect) return;
    let list = props.defaultSelect.split(",");
    console.log(list);
    const rows = [];
    list.forEach(val => {
      const data = tableData.list.find(item => item.ip == val);
      console.log(data);
      console.log(val);
      if (data) {
        rows.push(data);
      }
    });
    console.log(rows);
    if (heTableRef.value) {
      console.log("rows", rows);
      rows.forEach(row => {
        heTableRef.value.tableRef!.toggleRowSelection(row, undefined, false);
      });
    }
    emit("update", {
      idList: [],
      rowList: rows
    });
  }, 1000);
});
</script>

<template>
  <div style="padding: 16px">
    <he-table
      @handle-current-change="loadDataCb"
      :total="tableData.total"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="true"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="false"
      @select="selectCb"
      ref="heTableRef"
      :maxMultipleNum="maxMultipleNum"
      :maxMultipleNumTip="false"
    >
      <template #0Default="{ data }">
        {{ data.$index + 1 }}
      </template>
      <template #8Default="{ data }">
        {{ formatDate(data.row[8]) }}
      </template>
      <template #4Default="{ data }">
        {{ agrMap.get(data.row[4]) }}
      </template>
      <template #operationDefault="{ data }">
        <UpdateForm
          :row-data="{
            ...data.row
          }"
          :title="`编辑`"
          @success="loadDataCb"
        >
          <base-button type="edit_text"></base-button>
        </UpdateForm>
        <base-button @click="deleteCb(data.row.id)" type="del_text"></base-button>
      </template>
    </he-table>
  </div>
</template>
